package com.mm.cloth.fragment;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.mm.cloth.AddMatchActivity;
import com.mm.cloth.EditMatchActivity;
import com.mm.cloth.MatchDetailActivity;
import com.mm.cloth.OutfitListActivity;
import com.mm.cloth.R;
import com.mm.cloth.adapter.CategoryAdapter;
import com.mm.cloth.adapter.ClothesAdapter;
import com.mm.cloth.adapter.MatchAdapter;
import com.mm.cloth.adapter.SeasonAdapter;
import com.mm.cloth.api.ApiClient;
import com.mm.cloth.api.ApiService;
import com.mm.cloth.model.Category;
import com.mm.cloth.model.Clothes;
import com.mm.cloth.model.Match;
import com.mm.cloth.model.Season;
import com.mm.cloth.model.response.ApiResponse;
import com.mm.cloth.model.response.ClothesListResponse;
import com.mm.cloth.utils.LoginCheckUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MatchFragment extends Fragment {

    private static final String TAG = "MatchFragment";

    // UI组件
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView rvCategories;
    private RecyclerView rvClothes;
    private RecyclerView rvSeasons;
    private View clothesListView;
    private View boardView;
    private TextView tvCategoryTitle;
    private TextView tvEmpty;
    private FloatingActionButton fabAdd;
    private ViewGroup boardContainer;
    private TextView tvBoardEmpty;
    private TextView tvDebugInfo;
    private TextView btnCloseClothes;
    private View btnSave;
    private View btnOutfitList;
    private View btnCancel;
    private FrameLayout categoryContainer;
    private ImageButton btnToggleCategory;

    // 数据
    private CategoryAdapter categoryAdapter;
    private ClothesAdapter clothesAdapter;
    private SeasonAdapter seasonAdapter;
    private List<Category> categories = new ArrayList<>();
    private List<Clothes> allClothes = new ArrayList<>();
    private List<Clothes> filteredClothes = new ArrayList<>();
    private List<Season> seasons = new ArrayList<>();
    private List<String> seasonStrings = new ArrayList<>(); // 用于SeasonAdapter的字符串列表
    private List<BoardItem> boardItems = new ArrayList<>();
    private int currentCategory = 0; // 当前选中的分类ID，默认为0（全部）
    private String currentSeason = "all"; // 当前选中的季节，默认为all（全部）
    private boolean showClothesList = false;
    private boolean isLoading = false;
    private boolean isCategoryLoading = false;
    private boolean isEditMode = false;
    private String editOutfitId = null;
    private Match currentOutfit = null;
    private boolean isCategoryCollapsed = false; // 分类列表是否收起

    // 拖动相关变量
    private boolean isDragging = false;
    private float startX = 0;
    private float startY = 0;
    private int currentIndex = -1;

    // 底部弹窗
    private BottomSheetDialog saveDialog;
    private String outfitName = "";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_match, container, false);
        initViews(view);
        setupListeners();
        initSeasons();
        loadCategories();
        loadClothesByCategory(currentCategory);
        return view;
    }

    private void initViews(View view) {
        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);
        categoryContainer = view.findViewById(R.id.categoryContainer);
        rvCategories = view.findViewById(R.id.rvCategories);
        btnToggleCategory = view.findViewById(R.id.btnToggleCategory);
        clothesListView = view.findViewById(R.id.clothesListView);
        boardView = view.findViewById(R.id.boardView);
        tvCategoryTitle = view.findViewById(R.id.tvCategoryTitle);
        rvClothes = view.findViewById(R.id.rvClothes);
        rvSeasons = view.findViewById(R.id.rvSeasons);
        tvEmpty = view.findViewById(R.id.tvEmpty);
        fabAdd = view.findViewById(R.id.fabAdd);
        boardContainer = view.findViewById(R.id.boardContainer);
        tvBoardEmpty = view.findViewById(R.id.tvBoardEmpty);
        tvDebugInfo = view.findViewById(R.id.tvDebugInfo);
        btnCloseClothes = view.findViewById(R.id.btnCloseClothes);
        btnSave = view.findViewById(R.id.btnSave);
        btnOutfitList = view.findViewById(R.id.btnOutfitList);
        btnCancel = view.findViewById(R.id.btnCancel);

        // 初始状态设置
        clothesListView.setVisibility(View.GONE);
        boardView.setVisibility(View.VISIBLE);
        
        // 确保收起/展开按钮可见
        if (btnToggleCategory != null) {
            btnToggleCategory.setVisibility(View.VISIBLE);
        }
    }

    private void setupListeners() {
        // 设置下拉刷新
        swipeRefreshLayout.setOnRefreshListener(() -> {
            loadClothesByCategory(currentCategory);
        });

        // 设置添加按钮点击事件
        fabAdd.setOnClickListener(v -> {
            if (LoginCheckUtil.checkLoginAndRedirect(getActivity(), true)) {
                Intent intent = new Intent(getActivity(), AddMatchActivity.class);
                startActivity(intent);
            }
        });

        // 关闭衣物列表按钮
        btnCloseClothes.setOnClickListener(v -> {
            closeClothesList();
        });

        // 保存搭配按钮
        btnSave.setOnClickListener(v -> {
            saveOutfit();
        });

        // 搭配列表按钮
        btnOutfitList.setOnClickListener(v -> {
            showOutfitList();
        });

        // 取消编辑按钮
        btnCancel.setOnClickListener(v -> {
            cancelEdit();
        });
        
        // 收起/展开分类列表按钮
        btnToggleCategory.setOnClickListener(v -> {
            toggleCategoryPanel();
        });
    }
    
    /**
     * 切换分类面板的收起/展开状态
     */
    private void toggleCategoryPanel() {
        if (isCategoryCollapsed) {
            // 展开分类列表
            expandCategoryPanel();
        } else {
            // 收起分类列表
            collapseCategoryPanel();
        }
    }
    
    /**
     * 收起分类面板
     */
    private void collapseCategoryPanel() {
        // 记录当前宽度
        final int startWidth = categoryContainer.getWidth();
        final int endWidth = btnToggleCategory.getWidth();
        
        // 创建动画
        ValueAnimator animator = ValueAnimator.ofInt(startWidth, endWidth);
        animator.setDuration(300);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        
        animator.addUpdateListener(animation -> {
            int value = (int) animation.getAnimatedValue();
            ViewGroup.LayoutParams params = categoryContainer.getLayoutParams();
            params.width = value;
            categoryContainer.setLayoutParams(params);
        });
        
        animator.start();
        
        // 更改图标为右箭头并添加旋转动画
        btnToggleCategory.setImageResource(R.drawable.ic_arrow_right);
        btnToggleCategory.animate()
                .rotation(180)
                .setDuration(300)
                .start();
        
        // 更新状态
        isCategoryCollapsed = true;
        
        // 隐藏分类列表
        rvCategories.setVisibility(View.GONE);
    }
    
    /**
     * 展开分类面板
     */
    private void expandCategoryPanel() {
        // 记录当前宽度
        final int startWidth = categoryContainer.getWidth();
        final int endWidth = getResources().getDimensionPixelSize(R.dimen.category_panel_width);
        
        // 创建动画
        ValueAnimator animator = ValueAnimator.ofInt(startWidth, endWidth);
        animator.setDuration(300);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        
        animator.addUpdateListener(animation -> {
            int value = (int) animation.getAnimatedValue();
            ViewGroup.LayoutParams params = categoryContainer.getLayoutParams();
            params.width = value;
            categoryContainer.setLayoutParams(params);
        });
        
        animator.start();
        
        // 更改图标为左箭头并添加旋转动画
        btnToggleCategory.setImageResource(R.drawable.ic_arrow_left);
        btnToggleCategory.animate()
                .rotation(0)
                .setDuration(300)
                .start();
        
        // 更新状态
        isCategoryCollapsed = false;
        
        // 显示分类列表
        rvCategories.setVisibility(View.VISIBLE);
    }

    private void initSeasons() {
        // 添加季节数据
        seasons.add(new Season("all", "全部"));
        seasons.add(new Season("spring", "春季"));
        seasons.add(new Season("summer", "夏季"));
        seasons.add(new Season("autumn", "秋季"));
        seasons.add(new Season("winter", "冬季"));
        
        // 转换为字符串列表，供SeasonAdapter使用
        seasonStrings = new ArrayList<>();
        for (Season season : seasons) {
            seasonStrings.add(season.getName());
        }

        // 创建适配器
        seasonAdapter = new SeasonAdapter(getContext(), seasonStrings);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        rvSeasons.setLayoutManager(layoutManager);
        rvSeasons.setAdapter(seasonAdapter);

        // 设置点击事件
        seasonAdapter.setOnSeasonClickListener(seasonName -> {
            // 根据名称找到对应的季节值
            String seasonValue = "all";
            for (Season season : seasons) {
                if (season.getName().equals(seasonName)) {
                    seasonValue = season.getValue();
                    break;
                }
            }
            currentSeason = seasonValue;
            filterClothes();
        });
    }

    private void loadCategories() {
        Log.d(TAG, "开始加载分类列表");
        isCategoryLoading = true;

        // 添加默认的"全部"分类
        categories.clear();
        categories.add(new Category(0, "全部"));

        // 初始化适配器
        categoryAdapter = new CategoryAdapter(getContext(), categories);
        rvCategories.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        rvCategories.setAdapter(categoryAdapter);

        categoryAdapter.setOnCategoryClickListener(category -> {
            Log.d(TAG, "点击分类: " + category.getName() + " (ID: " + category.getId() + ")");
            Log.d(TAG, "当前分类总数: " + categories.size());
            toggleCategory(category.getId());
        });

        // 从API加载分类列表
        loadCategoriesFromApi();
    }

    /**
     * 从API加载分类列表
     */
    private void loadCategoriesFromApi() {
        Log.d(TAG, "MatchFragment从API加载分类列表");

        ApiService apiService = ApiClient.getInstance().getApiService();

        apiService.getCategoryList().enqueue(new retrofit2.Callback<ApiResponse<List<Category>>>() {
            @Override
            public void onResponse(retrofit2.Call<ApiResponse<List<Category>>> call,
                                 retrofit2.Response<ApiResponse<List<Category>>> response) {
                if (getActivity() == null) return;

                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<List<Category>> apiResponse = response.body();

                    if (apiResponse.getCode() == 200 && apiResponse.getData() != null) {
                        List<Category> serverCategories = apiResponse.getData();

                        Log.d(TAG, "从API获取到 " + serverCategories.size() + " 个分类");

                        // 清除除了"全部"分类之外的其他分类
                        while (categories.size() > 1) {
                            categories.remove(1);
                        }

                        // 添加从服务器获取的分类
                        categories.addAll(serverCategories);

                        // 通知适配器数据已更改
                        categoryAdapter.notifyDataSetChanged();

                        Log.d(TAG, "分类列表更新完成，总数: " + categories.size());
                    } else {
                        Log.w(TAG, "API返回错误: " + apiResponse.getCode() + " - " + apiResponse.getMessage());
                        loadDefaultCategories();
                    }
                } else {
                    Log.w(TAG, "HTTP请求失败: " + response.code());
                    loadDefaultCategories();
                }

                isCategoryLoading = false;
            }

            @Override
            public void onFailure(retrofit2.Call<ApiResponse<List<Category>>> call, Throwable t) {
                Log.e(TAG, "加载分类列表失败: " + t.getMessage(), t);
                if (getActivity() == null) return;

                // 网络请求失败，使用默认分类
                loadDefaultCategories();
                isCategoryLoading = false;
            }
        });
    }

    /**
     * 加载默认分类作为后备方案
     */
    private void loadDefaultCategories() {
        Log.d(TAG, "使用默认分类列表");

        // 清除除了"全部"分类之外的其他分类
        while (categories.size() > 1) {
            categories.remove(1);
        }

        // 添加默认分类
        categories.add(new Category(1, "上衣"));
        categories.add(new Category(2, "下装"));
        categories.add(new Category(3, "连衣裙"));
        categories.add(new Category(4, "外套"));
        categories.add(new Category(5, "鞋子"));
        categories.add(new Category(6, "配饰"));

        // 通知适配器数据已更改
        categoryAdapter.notifyDataSetChanged();
    }

    private void toggleCategory(int categoryId) {
        Log.d(TAG, "切换分类: " + categoryId + ", 当前分类: " + currentCategory);

        if (currentCategory == categoryId) {
            showClothesList = !showClothesList;
        } else {
            currentCategory = categoryId;
            showClothesList = true;
            loadClothesByCategory(categoryId);
        }

        updateUI();
    }

    private void updateUI() {
        if (showClothesList) {
            clothesListView.setVisibility(View.VISIBLE);
            boardView.setVisibility(View.GONE);
            tvCategoryTitle.setText(getCategoryNameById(currentCategory) + "列表");
        } else {
            clothesListView.setVisibility(View.GONE);
            boardView.setVisibility(View.VISIBLE);
        }

        categoryAdapter.setSelectedCategory(currentCategory);
    }

    private void loadClothesByCategory(int categoryId) {
        Log.d(TAG, "加载分类衣物, categoryId: " + categoryId + ", season: " + currentSeason);
        
        // 添加登录状态检查
        if (!LoginCheckUtil.isLoggedIn(getActivity())) {
            Log.d(TAG, "用户未登录，停止加载衣物数据");
            // 停止加载状态
            isLoading = false;
            swipeRefreshLayout.setRefreshing(false);
            
            // 清空数据
            allClothes.clear();
            filteredClothes.clear();
            if (clothesAdapter != null) {
                clothesAdapter.notifyDataSetChanged();
            }
            
            // 显示空状态
            updateEmptyView();
            return;
        }
        
        isLoading = true;
        swipeRefreshLayout.setRefreshing(true);

        // 从API加载衣物数据
        loadClothesFromApi(categoryId);
    }

    /**
     * 从API加载衣物数据
     */
    private void loadClothesFromApi(int categoryId) {
        Log.d(TAG, "从API加载衣物数据, categoryId: " + categoryId + ", season: " + currentSeason);

        ApiService apiService = ApiClient.getInstance().getApiService();

        // 转换季节参数
        String seasonParam = "all".equals(currentSeason) ? null : currentSeason;
        Integer categoryParam = categoryId == 0 ? null : categoryId;

        // 调用API获取衣物列表
        apiService.getClothesList(
                1, // 页码，搭配页面一次性加载所有数据
                1000, // 页大小，设置较大值以获取所有数据
                categoryParam,
                seasonParam,
                null // 搭配页面不需要搜索功能
        ).enqueue(new retrofit2.Callback<ApiResponse<ClothesListResponse>>() {
            @Override
            public void onResponse(retrofit2.Call<ApiResponse<ClothesListResponse>> call,
                                 retrofit2.Response<ApiResponse<ClothesListResponse>> response) {
                if (getActivity() == null) return;

                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<ClothesListResponse> apiResponse = response.body();

                    if (apiResponse.getCode() == 200 && apiResponse.getData() != null) {
                        ClothesListResponse data = apiResponse.getData();
                        List<Clothes> newClothes = data.getList();

                        Log.d(TAG, "API请求成功，获取到 " + (newClothes != null ? newClothes.size() : 0) + " 条数据");

                        if (newClothes == null) {
                            newClothes = new ArrayList<>();
                        }

                        // 更新数据
                        allClothes.clear();
                        allClothes.addAll(newClothes);

                        // 应用筛选
                        filterClothes();

                        // 更新UI状态
                        isLoading = false;
                        swipeRefreshLayout.setRefreshing(false);

                        Log.d(TAG, "衣物数据更新完成，总数: " + allClothes.size());
                    } else {
                        // API返回错误
                        handleApiError(apiResponse.getCode(), apiResponse.getMessage());
                    }
                } else {
                    // HTTP请求失败
                    handleApiError(response.code(), "HTTP请求失败");
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ApiResponse<ClothesListResponse>> call, Throwable t) {
                Log.e(TAG, "API请求失败: " + t.getMessage(), t);
                if (getActivity() == null) return;

                handleApiError(500, "网络请求失败: " + t.getMessage());
            }
        });
    }

    /**
     * 处理API错误
     */
    private void handleApiError(int code, String message) {
        // 更新UI状态
        isLoading = false;
        swipeRefreshLayout.setRefreshing(false);

        // 如果是网络错误，使用模拟数据作为后备
        if (code == 500) {
            Log.d(TAG, "网络错误，使用模拟数据");
            allClothes = getSimulatedClothes();
            filterClothes();
            Toast.makeText(getContext(), "网络连接失败，显示模拟数据", Toast.LENGTH_SHORT).show();
        } else {
            // 显示错误信息
            String errorMsg = "加载失败";
            if (code == 401) {
                errorMsg = "登录已过期，请重新登录";
            } else if (message != null && !message.isEmpty()) {
                errorMsg = message;
            }

            Toast.makeText(getContext(), errorMsg, Toast.LENGTH_SHORT).show();

            // 使用模拟数据作为后备
            allClothes = getSimulatedClothes();
            filterClothes();
        }
    }

    private void filterClothes() {
        filteredClothes.clear();

        // 由于API调用时已经按分类和季节筛选了，这里直接使用所有数据
        // 但为了保持代码的一致性，仍然保留筛选逻辑

        // 分类筛选
        if (currentCategory != 0) { // 0表示"全部"分类
            String categoryName = getCategoryNameById(currentCategory);
            for (Clothes clothes : allClothes) {
                // 根据分类名称进行匹配
                if (clothes.getCategory() != null &&
                    (clothes.getCategory().equals(categoryName) ||
                     clothes.getCategory().equals(String.valueOf(currentCategory)))) {
                    filteredClothes.add(clothes);
                }
            }
        } else {
            filteredClothes.addAll(allClothes);
        }

        // 季节筛选
        if (!currentSeason.equals("all")) {
            List<Clothes> seasonFiltered = new ArrayList<>();
            for (Clothes clothes : filteredClothes) {
                if (currentSeason.equals(clothes.getSeason())) {
                    seasonFiltered.add(clothes);
                }
            }
            filteredClothes.clear();
            filteredClothes.addAll(seasonFiltered);
        }

        // 更新适配器
        if (clothesAdapter == null) {
            setupClothesRecyclerView();
        } else {
            clothesAdapter.updateData(filteredClothes);
        }

        updateEmptyView();
    }
    
    private void setupClothesRecyclerView() {
        clothesAdapter = new ClothesAdapter(getContext(), filteredClothes);
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
        rvClothes.setLayoutManager(layoutManager);
        rvClothes.setAdapter(clothesAdapter);
        
        clothesAdapter.setOnItemClickListener(new ClothesAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Clothes clothes) {
                // 点击衣物项的处理
                Toast.makeText(getContext(), "选择了: " + clothes.getName(), Toast.LENGTH_SHORT).show();
            }
            
            @Override
            public void onItemLongClick(Clothes clothes) {
                // 长按添加到画板
                addToBoard(clothes);
            }
        });
    }
    
    private void updateEmptyView() {
        if (filteredClothes.isEmpty()) {
            tvEmpty.setVisibility(View.VISIBLE);
            rvClothes.setVisibility(View.GONE);
        } else {
            tvEmpty.setVisibility(View.GONE);
            rvClothes.setVisibility(View.VISIBLE);
        }
    }
    
    private void closeClothesList() {
        showClothesList = false;
        updateUI();
    }
    
    private void addToBoard(Clothes clothes) {
        if (getActivity() == null) return;
        
        if (LoginCheckUtil.checkLoginAndRedirect(getActivity(), true)) {
            // 创建新的画板项
            BoardItem boardItem = new BoardItem();
            boardItem.clothes = clothes;
            
            // 计算初始位置 - 放在画板中央
            if (boardContainer != null) {
                int boardWidth = boardContainer.getWidth();
                int boardHeight = boardContainer.getHeight();
                // 默认衣物宽高约为120dp
                int estimatedItemWidth = 120;
                int estimatedItemHeight = 120;
                
                // 计算中央位置，并添加一些随机偏移，避免所有衣物堆在一起
                float randomOffsetX = (float)(Math.random() * 100 - 50); // -50到50的随机偏移
                float randomOffsetY = (float)(Math.random() * 100 - 50);
                
                boardItem.x = (boardWidth - estimatedItemWidth) / 2 + randomOffsetX;
                boardItem.y = (boardHeight - estimatedItemHeight) / 2 + randomOffsetY;
            } else {
                // 默认位置
                boardItem.x = 0;
                boardItem.y = 0;
            }
            
            boardItem.scale = 1.0f;
            
            // 添加到画板
            boardItems.add(boardItem); // 先添加到数据列表中
            addItemToBoard(boardItem);
            
            // 更新调试信息和空视图状态
            updateDebugInfo();
            updateBoardEmptyView();
            
            Toast.makeText(getContext(), "已添加到搭配展示", Toast.LENGTH_SHORT).show();
        }
    }

    private void addItemToBoard(BoardItem boardItem) {
        // 创建一个新的视图来表示搭配板上的衣物
        View itemView = LayoutInflater.from(getContext()).inflate(R.layout.item_board_clothes, boardContainer, false);
        ImageView imageView = itemView.findViewById(R.id.ivClothes);
        View btnRemove = itemView.findViewById(R.id.btnRemove);
        View btnScaleUp = itemView.findViewById(R.id.btnScaleUp);
        View btnScaleDown = itemView.findViewById(R.id.btnScaleDown);
        
        // 设置图片
        if (getContext() != null && isAdded()) {
            RequestOptions requestOptions = new RequestOptions()
                .placeholder(R.drawable.placeholder_clothes)
                .error(R.drawable.error_image);
                
            Glide.with(requireContext())
                .load(boardItem.clothes.getImageUrl())
                .apply(requestOptions)
                .into(imageView);
        }
            
        // 设置位置和缩放
        ViewGroup.LayoutParams params = itemView.getLayoutParams();
        if (params == null) {
            params = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            );
        }
        itemView.setLayoutParams(params);
        
        // 设置初始位置
        itemView.setX(boardItem.x);
        itemView.setY(boardItem.y);
        itemView.setScaleX(boardItem.scale);
        itemView.setScaleY(boardItem.scale);
        
        // 设置拖动事件
        itemView.setOnTouchListener((v, event) -> {
            int index = boardItems.indexOf(boardItem);
            if (index == -1) return false;
            
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    isDragging = true;
                    currentIndex = index;
                    startX = event.getRawX() - boardItem.x;
                    startY = event.getRawY() - boardItem.y;
                    // 将当前拖动的项目提到最上层
                    v.bringToFront();
                    return true;
                    
                case MotionEvent.ACTION_MOVE:
                    if (isDragging && currentIndex == index) {
                        float newX = event.getRawX() - startX;
                        float newY = event.getRawY() - startY;
                        
                        // 获取边界限制
                        int boardWidth = boardContainer.getWidth();
                        int boardHeight = boardContainer.getHeight();
                        int viewWidth = (int)(v.getWidth() * boardItem.scale);
                        int viewHeight = (int)(v.getHeight() * boardItem.scale);
                        
                        // 考虑缩放因素，预留一些边距
                        int margin = 20;
                        
                        // 限制X坐标不超出边界
                        newX = Math.max(-margin, newX);
                        newX = Math.min(boardWidth - viewWidth + margin, newX);
                        
                        // 限制Y坐标不超出边界
                        newY = Math.max(-margin, newY);
                        newY = Math.min(boardHeight - viewHeight + margin, newY);
                        
                        // 更新位置
                        boardItem.x = newX;
                        boardItem.y = newY;
                        v.setX(newX);
                        v.setY(newY);
                        return true;
                    }
                    break;
                    
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    isDragging = false;
                    currentIndex = -1;
                    return true;
            }
            return false;
        });
        
        // 设置删除按钮
        btnRemove.setOnClickListener(v -> removeFromBoard(boardItem));
        
        // 设置缩放按钮
        btnScaleUp.setOnClickListener(v -> {
            if (boardItem.scale < 3.0f) {
                boardItem.scale = Math.min(3.0f, boardItem.scale + 0.2f);
                itemView.setScaleX(boardItem.scale);
                itemView.setScaleY(boardItem.scale);
                // 调整位置确保不超出边界
                adjustItemPosition(boardItem, itemView);
            }
        });
        
        btnScaleDown.setOnClickListener(v -> {
            if (boardItem.scale > 0.5f) {
                boardItem.scale = Math.max(0.5f, boardItem.scale - 0.2f);
                itemView.setScaleX(boardItem.scale);
                itemView.setScaleY(boardItem.scale);
                // 调整位置确保不超出边界
                adjustItemPosition(boardItem, itemView);
            }
        });
        
        // 将视图添加到容器
        boardContainer.addView(itemView);
        boardItem.view = itemView;
    }

    /**
     * 调整衣物项的位置，确保不超出边界
     */
    private void adjustItemPosition(BoardItem boardItem, View itemView) {
        if (boardContainer == null || itemView == null) return;
        
        int boardWidth = boardContainer.getWidth();
        int boardHeight = boardContainer.getHeight();
        int viewWidth = (int)(itemView.getWidth() * boardItem.scale);
        int viewHeight = (int)(itemView.getHeight() * boardItem.scale);
        int margin = 20;
        
        // 调整X坐标
        float newX = boardItem.x;
        newX = Math.max(-margin, newX);
        newX = Math.min(boardWidth - viewWidth + margin, newX);
        
        // 调整Y坐标
        float newY = boardItem.y;
        newY = Math.max(-margin, newY);
        newY = Math.min(boardHeight - viewHeight + margin, newY);
        
        // 更新位置
        boardItem.x = newX;
        boardItem.y = newY;
        itemView.setX(newX);
        itemView.setY(newY);
    }

    private void removeFromBoard(BoardItem boardItem) {
        // 从容器中移除视图
        if (boardItem.view != null) {
            boardContainer.removeView(boardItem.view);
        }
        
        // 从数据中移除
        boardItems.remove(boardItem);
        
        // 更新调试信息
        updateDebugInfo();
        
        // 更新空状态提示
        updateBoardEmptyView();
    }

    private void updateDebugInfo() {
        tvDebugInfo.setText("已加载图片数: " + boardItems.size());
    }

    private void updateBoardEmptyView() {
        if (boardItems.isEmpty()) {
            tvBoardEmpty.setVisibility(View.VISIBLE);
        } else {
            tvBoardEmpty.setVisibility(View.GONE);
        }
    }

    private void saveOutfit() {
        if (!LoginCheckUtil.checkLoginAndRedirect(getActivity(), true)) {
            return;
        }
        
        if (boardItems.isEmpty()) {
            Toast.makeText(getContext(), "请先添加衣物", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 创建保存对话框
        showSaveDialog();
    }

    private void showSaveDialog() {
        if (saveDialog == null) {
            saveDialog = new BottomSheetDialog(requireContext());
            View dialogView = getLayoutInflater().inflate(R.layout.dialog_save_outfit, null);
            saveDialog.setContentView(dialogView);
            
            // 设置标题
            TextView tvTitle = dialogView.findViewById(R.id.tvDialogTitle);
            tvTitle.setText(isEditMode ? "编辑搭配" : "保存搭配");
            
            // 设置输入框
            EditText etName = dialogView.findViewById(R.id.etOutfitName);
            TextView tvCharCount = dialogView.findViewById(R.id.tvCharCount);
            
            // 设置字符计数
            etName.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
                
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {}
                
                @Override
                public void afterTextChanged(Editable s) {
                    tvCharCount.setText(s.length() + "/20");
                }
            });
            
            if (isEditMode && currentOutfit != null) {
                etName.setText(currentOutfit.getTitle());
            }
            
            // 设置预览区域
            RecyclerView rvPreview = dialogView.findViewById(R.id.rvPreview);
            // 这里可以添加预览适配器的实现
            
            // 设置按钮
            MaterialButton btnCancel = dialogView.findViewById(R.id.btnCancel);
            MaterialButton btnConfirm = dialogView.findViewById(R.id.btnConfirm);
            
            btnCancel.setOnClickListener(v -> saveDialog.dismiss());
            
            btnConfirm.setOnClickListener(v -> {
                String name = etName.getText().toString().trim();
                if (name.isEmpty()) {
                    Toast.makeText(getContext(), "请输入搭配名称", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                outfitName = name;
                confirmSave();
                saveDialog.dismiss();
            });
            
            // 设置关闭按钮
            dialogView.findViewById(R.id.btnClose).setOnClickListener(v -> saveDialog.dismiss());
        }
        
        saveDialog.show();
    }

    private void confirmSave() {
        if (outfitName.isEmpty()) {
            Toast.makeText(getContext(), "请输入搭配名称", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (boardItems.isEmpty()) {
            Toast.makeText(getContext(), "请选择衣物", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 准备搭配数据
        Map<String, Object> outfitData = new HashMap<>();
        outfitData.put("name", outfitName);
        
        List<Map<String, Object>> clothesData = new ArrayList<>();
        List<Map<String, Object>> positionsData = new ArrayList<>();
        
        for (BoardItem item : boardItems) {
            // 衣物数据
            Map<String, Object> clothesMap = new HashMap<>();
            clothesMap.put("id", item.clothes.getId());
            clothesMap.put("name", item.clothes.getName());
            clothesMap.put("image", item.clothes.getImageUrl());
            clothesData.add(clothesMap);
            
            // 位置数据
            Map<String, Object> positionMap = new HashMap<>();
            positionMap.put("id", item.clothes.getId());
            positionMap.put("image", item.clothes.getImageUrl());
            positionMap.put("x", item.x);
            positionMap.put("y", item.y);
            positionMap.put("scale", item.scale);
            positionsData.add(positionMap);
        }
        
        outfitData.put("clothes", clothesData);
        outfitData.put("positions", positionsData);
        
        // 显示加载提示
        Toast.makeText(getContext(), "保存中...", Toast.LENGTH_SHORT).show();
        
        // 模拟API调用
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            // 模拟保存成功
            Toast.makeText(getContext(), "保存成功", Toast.LENGTH_SHORT).show();
            
            // 重置状态
            resetOutfit();
        }, 1500);
    }

    private void resetOutfit() {
        outfitName = "";
        
        // 清空搭配板
        for (BoardItem item : new ArrayList<>(boardItems)) {
            if (item.view != null) {
                boardContainer.removeView(item.view);
            }
        }
        boardItems.clear();
        
        // 更新UI
        updateDebugInfo();
        updateBoardEmptyView();
        
        // 重置分类
        currentCategory = 0;
        showClothesList = false;
        updateUI();
        loadClothesByCategory(currentCategory);
    }

    private void showOutfitList() {
        if (!LoginCheckUtil.checkLoginAndRedirect(getActivity(), true)) {
            return;
        }
        
        // 跳转到搭配列表页面
        try {
            Intent intent = new Intent(getActivity(), OutfitListActivity.class);
            startActivity(intent);
            // 添加日志以便调试
            Log.d(TAG, "已尝试跳转到搭配列表页面");
            // 添加提示
            Toast.makeText(getContext(), "正在打开搭配列表", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Log.e(TAG, "跳转出错", e);
            Toast.makeText(getContext(), "跳转出错: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void cancelEdit() {
        if (isEditMode) {
            new AlertDialog.Builder(requireContext())
                .setTitle("提示")
                .setMessage("确定要取消编辑吗？未保存的修改将会丢失")
                .setPositiveButton("确定", (dialog, which) -> {
                    resetOutfit();
                    if (getActivity() != null) {
                        getActivity().onBackPressed();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
        }
    }

    private List<Clothes> getSimulatedClothes() {
        List<Clothes> clothesList = new ArrayList<>();
        
        // 模拟一些衣物数据 - 修改构造函数调用以匹配Clothes类的定义
        Clothes tshirt = new Clothes();
        tshirt.setId(1);
        tshirt.setName("白色T恤");
        tshirt.setCategory("1"); // 上衣
        tshirt.setImageUrl("https://example.com/tshirt.jpg");
        tshirt.setSeason("summer");
        clothesList.add(tshirt);
        
        Clothes jeans = new Clothes();
        jeans.setId(2);
        jeans.setName("牛仔裤");
        jeans.setCategory("2"); // 下装
        jeans.setImageUrl("https://example.com/jeans.jpg");
        jeans.setSeason("all");
        clothesList.add(jeans);
        
        Clothes dress = new Clothes();
        dress.setId(3);
        dress.setName("黑色连衣裙");
        dress.setCategory("3"); // 连衣裙
        dress.setImageUrl("https://example.com/dress.jpg");
        dress.setSeason("spring");
        clothesList.add(dress);
        
        // 添加更多衣物
        Clothes jacket = new Clothes();
        jacket.setId(4);
        jacket.setName("皮夹克");
        jacket.setCategory("4"); // 外套
        jacket.setImageUrl("https://example.com/jacket.jpg");
        jacket.setSeason("autumn");
        clothesList.add(jacket);
        
        Clothes shoes = new Clothes();
        shoes.setId(5);
        shoes.setName("运动鞋");
        shoes.setCategory("5"); // 鞋子
        shoes.setImageUrl("https://example.com/shoes.jpg");
        shoes.setSeason("all");
        clothesList.add(shoes);
        
        Clothes scarf = new Clothes();
        scarf.setId(6);
        scarf.setName("围巾");
        scarf.setCategory("6"); // 配饰
        scarf.setImageUrl("https://example.com/scarf.jpg");
        scarf.setSeason("winter");
        clothesList.add(scarf);
        
        return clothesList;
    }

    private String getCategoryNameById(int categoryId) {
        for (Category category : categories) {
            if (category.getId() == categoryId) {
                return category.getName();
            }
        }
        return "全部";
    }

    @Override
    public void onResume() {
        super.onResume();

        Log.d(TAG, "MatchFragment onResume");

        // 检查是否需要在登录后刷新
        checkAndRefreshAfterLogin();

        // 检查用户是否刚登录，如果是则刷新数据
        if (LoginCheckUtil.isJustLoggedIn()) {
            loadClothesByCategory(currentCategory);
            LoginCheckUtil.resetJustLoggedInFlag();
        }

        // 每次onResume时都检查分类数据是否需要刷新
        // 如果分类列表为空或只有"全部"分类，则重新加载
        if (isVisible() && getUserVisibleHint()) {
            if (categories.size() <= 1) {
                Log.d(TAG, "分类数据不完整，重新加载分类列表");
                loadCategoriesFromApi();
            } else {
                Log.d(TAG, "分类数据完整，当前分类数量: " + categories.size());
            }
        } else {
            Log.d(TAG, "Fragment不可见，跳过分类数据检查");
        }

        // 调整所有衣物的位置，确保在屏幕旋转等情况下位置正确
        adjustAllItemsPosition();
    }

    /**
     * 检查是否需要在登录后刷新数据
     */
    private void checkAndRefreshAfterLogin() {
        if (getContext() != null) {
            boolean needRefreshAfterLogin = getContext().getSharedPreferences("app_state", Context.MODE_PRIVATE)
                    .getBoolean("need_refresh_after_login", false);

            if (needRefreshAfterLogin) {
                Log.d(TAG, "检测到登录后需要刷新，开始刷新数据");
                refreshDataAfterLogin();

                // 清除标记
                getContext().getSharedPreferences("app_state", Context.MODE_PRIVATE)
                        .edit()
                        .putBoolean("need_refresh_after_login", false)
                        .apply();
            }
        }
    }

    /**
     * 登录后刷新数据
     * 重新加载分类和衣物数据，确保显示用户的最新数据
     */
    public void refreshDataAfterLogin() {
        Log.d(TAG, "登录后刷新数据开始");

        // 重新加载分类数据
        loadCategoriesFromApi();

        // 重新加载衣物数据
        loadClothesByCategory(currentCategory);

        Log.d(TAG, "登录后刷新数据完成");
    }

    /**
     * 刷新分类数据
     * 当WardrobeFragment中的分类发生变化时调用
     */
    public void refreshCategories() {
        Log.d(TAG, "刷新分类数据");
        loadCategoriesFromApi();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        Log.d(TAG, "MatchFragment setUserVisibleHint: " + isVisibleToUser);

        if (isVisibleToUser && isResumed()) {
            // Fragment变为可见且已经Resume，检查分类数据
            checkAndLoadCategoriesIfNeeded();
        }
    }

    /**
     * 检查分类数据完整性
     * 如果数据不完整则重新加载
     */
    private void checkAndLoadCategoriesIfNeeded() {
        if (getActivity() == null) return;

        // 如果用户已登录但分类数据不完整，则重新加载
        if (LoginCheckUtil.isLoggedIn(getActivity())) {
            if (categories.size() <= 1) {
                Log.d(TAG, "用户已登录但分类数据不完整，重新加载");
                loadCategoriesFromApi();
            }
        } else {
            Log.d(TAG, "用户未登录，使用默认分类");
        }
    }
    
    /**
     * 调整所有衣物项的位置，确保不超出边界
     */
    private void adjustAllItemsPosition() {
        // 延迟执行，确保boardContainer已经完成布局
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            if (isAdded() && boardContainer != null) {
                for (BoardItem item : boardItems) {
                    if (item.view != null) {
                        adjustItemPosition(item, item.view);
                    }
                }
            }
        }, 300); // 延迟300毫秒，确保布局已完成
    }

    // 内部类，用于表示搭配板上的衣物项
    private static class BoardItem {
        Clothes clothes;
        float x;
        float y;
        float scale;
        View view;
    }
}